package cac.fenjian.resource.PointPackageSort.rest;

import cac.common.CreateCommonLog;
import cac.fenjian.resource.AoTask.MsConsole.dao.MsConsoleDao;
import cac.fenjian.resource.PointPackageSort.dao.PointPackageDao;
import cac.fenjian.resource.PointPackageSort.service.PointPackageSortService;
import cac.fenjian.resource.mssslshelves.dao.MsGkLogDao;
import com.cac.dme.adapter.rest.msg.ResponseMsg;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @className: PointPackageSortRest
 * @description: （描述这个类的作用）
 * @author:
 * @date: 2023/6/21 10:47:47 周三
 * @version: 1.0
 */
@RestController
@RequestMapping("/PointPackageSortRest")
@Slf4j
public class PointPackageSortRest {

    @Autowired
    private PointPackageDao pointPackageDao;
    @Autowired
    private PointPackageSortService pointPackageSortService;

    @Autowired
    private MsGkLogDao msGkLogDao;
    @Autowired
    private MsConsoleDao msConsoleDao;
    @Autowired
    private CreateCommonLog createCommonLog;
    @Value("${pathProperty.isTest}")
    private boolean isTest;


    /**
     * 修改备注
     */
    @PostMapping("saveRemark")
    //查询分拣台的缓存箱以及托盘
    public ResponseMsg saveRemark(@RequestBody HashMap map) {
        ResponseMsg responseMsg = new ResponseMsg();
        String receiveRemark = String.valueOf(map.get("receiveRemark"));
        String msAssginWorkbintoolRelId = String.valueOf(map.get("msAssginWorkbintoolRelId"));
        try {
            pointPackageDao.saveRemark(receiveRemark,msAssginWorkbintoolRelId);
            responseMsg.setRetCode("200");
        }catch (Exception e){
            responseMsg.setRetCode("201");
        }
        return responseMsg;
    }



    /***
     * 查询可以分拣的工作包
     * */
    @PostMapping("/searchPointPackage")
    public PageInfo searchPointPackage(@RequestBody HashMap map) {
        Map<String, Integer> page = (Map) map.get("page");
        PageHelper.startPage(page.get("currentPage"), page.get("pageSize"));
        List data = pointPackageDao.searchPointPackage((Map) map.get("queryParam"));
        PageInfo pageInfo = new PageInfo(data);
        return pageInfo;
    }
    /***
     * 查询可以分拣的AO
     * */
    @PostMapping("/searchPointAo")
    public PageInfo searchPointAo(@RequestBody HashMap map) {
        Map<String, Integer> page = (Map) map.get("page");
        PageHelper.startPage(page.get("currentPage"), page.get("pageSize"));
        List data = pointPackageDao.searchPointAo((Map) map.get("queryParam"));
        PageInfo pageInfo = new PageInfo(data);
        return pageInfo;
    }


    //指定工作包开始分拣
    @PostMapping("/startSorting")
    @Transactional
    public ResponseMsg startSorting(@RequestBody HashMap map) {
        ResponseMsg responseMsg = new ResponseMsg();
        log.info("param：" + map.toString());
        String packageId = (String) map.get("msTaskPackageId");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String IP = null;
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String account = (String) request.getSession().getAttribute("account");
        if (Objects.isNull(account)) {
            return responseMsg.setMessage("账户已过期，请重新登录").setRetCode("201");
        }
        //查询该工作包是否存在创建的箱子任务
        int c = pointPackageDao.queryPackageExistsWorkbin(packageId);
        if(c==0){
            return responseMsg.setMessage("此工作包没有可以创建的箱子任务，请查看配套信息!").setRetCode("201");
        }
        //判断是该工作包是否创建任务
        int cnt = pointPackageDao.queryPackageExistsTask(packageId);
        if(cnt>0){
            return responseMsg.setMessage("该工作包已经创建任务，请不要重复创建!").setRetCode("201");
        }
        HashMap param = new HashMap();
        param.put("i_package_id", packageId);
        param.put("i_ip", IP);
        //判断是否测试环境
        try {
            if (isTest) {
                pointPackageDao.callCreateTaskTest(param);
            } else {
                pointPackageDao.callCreateTask(param);
            }
            log.info("param:" + param);
            //获取存储过程返回值
            Integer count = (Integer) param.get("o_Return_Int");
            String msg = (String) param.get("o_Return_String");
            map.put("func","sort");
            if (count == 0) {
                responseMsg.setRetCode("200");
                //下发缓存箱出库指令
                map.put("boxType", "WORKBIN");
                //结束位置
                map.put("endCode", "xyssj" + msConsoleDao.findStartCode(IP, (String) map.get("boxType")));
                //首次下发命令标识符
                map.put("firstCall", "firstCall");
                //调用封装下发任务
                createCommonLog.callWCSInterface(map);
                //下发工作包出库指令
                map.replace("boxType", "TOOL");
                //结束位置
                map.put("endCode", "xyssj" + msConsoleDao.findStartCode(IP, (String) map.get("boxType")));
                //调用封装下发任务
                createCommonLog.callWCSInterface(map);
                responseMsg.setMessage("执行成功");
            } else {
                responseMsg.setRetCode("201");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            responseMsg.setMessage(msg);
            return responseMsg;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseMsg.setRetCode("201");
        }
    }

    @PostMapping("/startAoSorting")
    @Transactional
    public ResponseMsg startAoSorting(@RequestBody HashMap map) {
        ResponseMsg responseMsg = new ResponseMsg();
        log.info("param：" + map.toString());
        String msTaskAoId = (String) map.get("msTaskAoId");
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String IP = null;
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        String account = (String) request.getSession().getAttribute("account");
        if (Objects.isNull(account)) {
            return responseMsg.setMessage("账户已过期，请重新登录").setRetCode("201");
        }
        HashMap param = new HashMap();
        param.put("i_task_ao_id", msTaskAoId);
        param.put("i_ip", IP);
        //判断是否测试环境
        try {
            if (isTest) {
                pointPackageDao.callCreateAoTaskTest(param);
            } else {
                pointPackageDao.callCreateAoTask(param);
            }
            log.info("param:" + param);
            //获取存储过程返回值
            Integer count = (Integer) param.get("o_Return_Int");
            String msg = (String) param.get("o_Return_String");
            map.put("func","sort");
            if (count == 0) {
                responseMsg.setRetCode("200");
                //下发缓存箱出库指令
                map.put("boxType", "WORKBIN");
                //结束位置
                map.put("endCode", "xyssj" + msConsoleDao.findStartCode(IP, (String) map.get("boxType")));
                //首次下发命令标识符
                map.put("firstCall", "firstCall");
                //调用封装下发任务
                createCommonLog.callWCSInterface(map);
                //下发工作包出库指令
                map.replace("boxType", "TOOL");
                //结束位置
                map.put("endCode", "xyssj" + msConsoleDao.findStartCode(IP, (String) map.get("boxType")));
                //调用封装下发任务
                createCommonLog.callWCSInterface(map);
                responseMsg.setMessage("执行成功");
            } else {
                responseMsg.setRetCode("201");
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
            responseMsg.setMessage(msg);
            return responseMsg;
        } catch (Exception e) {
            e.printStackTrace();
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return responseMsg.setRetCode("201");
        }
    }


    @PostMapping("searchSortingTask")
    //查询分拣台的缓存箱以及托盘
    public List<HashMap> searchSortingTask() {
        String IP = null;
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        return pointPackageDao.searchSortingTask(IP);
    }

    //未创建任务的通过页面重新创建任务并调用分拣流量控制
    @PostMapping("/createGkLog")
    @Transactional
    public ResponseMsg createGkLog(@RequestBody HashMap map) {
        ResponseMsg responseMsg = new ResponseMsg();
        //查询未创建任务信息
        HashMap gkLog = pointPackageDao.searchGkLogSupple(map);
        if (Objects.isNull(gkLog)) {
            responseMsg.setMessage("此任务已经创建").setRetCode("201");
        } else {
            log.info("gklog------------------" + gkLog.toString());
            //校验是否已创建
            int cnt = pointPackageDao.searChpalletCode(gkLog);
            if (cnt > 0) {
                //未创建，创建gklog任务
                int rsl = msGkLogDao.creatLog(gkLog, gkLog.get("data").toString());
                if (rsl > 0) {
                    //修改未创建任务状态为已创建
                    pointPackageDao.updateMGkLogS(map);
                    String palletCode = gkLog.get("palletCode").toString();
                    if (palletCode.contains("11208003")){
                        //下发缓存箱出库指令
                        map.put("boxType", "WORKBIN");
                    }else {
                        //下发缓存箱出库指令
                        map.put("boxType", "TOOL");
                    }
                    map.put("func", "sort");
                    //结束位置
                    map.put("endCode", gkLog.get("endCode").toString());
                    //调用封装流量控制下发任务
                    HashMap data=createCommonLog.callWCSInterface(map);
                    if("200".equals(data.get("retCode"))){
                        responseMsg.setRetCode("200").setMessage(data.get("msg").toString());
                    }else {
                        responseMsg.setRetCode("201").setMessage(data.get("msg").toString());
                        TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                    }
                }
            } else {
                responseMsg.setMessage("暂时无法创建任务，请确认缓存箱在货架上或有未完成任务！").setRetCode("201");
            }
        }
        return responseMsg;
    }
    @PostMapping("queryWorkbinMaterial")
    public List<HashMap> queryWorkbinMaterial(@RequestBody HashMap map){
        return pointPackageDao.queryWorkbinMaterial(map);
    }
    @PostMapping("replaceMatchInfo")
    public ResponseMsg replaceMatchInfo(@RequestBody HashMap map){
        HashMap sourceMatch = (HashMap) map.get("sourceMatch");
        List<HashMap> replaceMatchList = (List<HashMap>) map.get("replaceMatchList");
        return pointPackageSortService.replaceMatchInfo(sourceMatch,replaceMatchList);
    }

    @PostMapping("packageTopMatch")
    public ResponseMsg packageTopMatch(@RequestBody HashMap map){
        return pointPackageSortService.packageTopMatch(map);
    }

    @PostMapping("/searchPointPallet")
    public PageInfo searchPointPallet(@RequestBody HashMap map) {
        Map<String, Integer> page = (Map) map.get("page");
        PageHelper.startPage(page.get("currentPage"), page.get("pageSize"));
        List data = pointPackageDao.queryPalletCode((Map) map.get("queryParam"));
        PageInfo pageInfo = new PageInfo(data);
        return pageInfo;
    }
    /**
     * 分拣操作--针对托盘进行分拣
     * */
    @PostMapping("startPalletSort")
    public HashMap startPalletSort(@RequestBody HashMap map){
        log.info(map.toString());
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String IP = null;
        if (request.getHeader("x-forwarded-for") == null) {
            IP = request.getRemoteAddr();
        } else {
            IP = request.getHeader("x-forwarded-for");
        }
        return pointPackageSortService.startPalletSort(map,IP);
    }

    /**
     * 分配托盘与箱子任务
     * **/
    @PostMapping("assginPallet")
    public HashMap assginPallet(){
        return pointPackageSortService.assginPallet();
    }
    @PostMapping("queryPalletTask")
    public PageInfo queryPalletTask(@RequestBody HashMap map){
        return pointPackageSortService.queryPalletTask(map);
    }

    /**
     * 针对托盘叫箱，新模式
     * map:{"toolCode":""}
     * **/
    @PostMapping("startPalletSortNewModel")
    public ResponseMsg startPalletSortNewModel(@RequestBody HashMap map){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = null;
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        } else {
            ip = request.getHeader("x-forwarded-for");
        }
        return pointPackageSortService.startPalletSortNewModel(map,ip);
    }

    /***
     * 针对工作包-扫箱子显示物料信息
     * **/
    @PostMapping("searchInventoryMaterialByWorkbinCode")
    public ResponseMsg<List<HashMap>> searchInventoryMaterialByWorkbinCode(@RequestBody HashMap map){
        ResponseMsg<List<HashMap>> responseMsg = new ResponseMsg<>();
        responseMsg.setResponseBody(pointPackageSortService.searchInventoryMaterialByWorkbinCode(map)).setRetCode("200");
        return responseMsg;
    }

    @PostMapping("queryCanReplaceWorkbin")
    public List<HashMap> queryCanReplaceWorkbin(@RequestBody HashMap map){
        return pointPackageDao.queryCanReplaceWorkbin(map);
    }
    @PostMapping("addHcx")
    public ResponseMsg addHcx(@RequestBody HashMap map){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String ip = null;
        if (request.getHeader("x-forwarded-for") == null) {
            ip = request.getRemoteAddr();
        } else {
            ip = request.getHeader("x-forwarded-for");
        }
        return pointPackageSortService.addHcx(map,ip);
    }
    @PostMapping("queryReplaceTool")
    public PageInfo queryReplaceTool(@RequestBody HashMap map){
        List list = pointPackageDao.queryReplaceTool(map);
        return new PageInfo(list);
    }
    /**
     * map:{targetToolCode:'替换后托盘',sourceToolCode:'替换前托盘'}
     * **/
    @PostMapping("replaceToolCode")
    public ResponseMsg replaceToolCode(@RequestBody HashMap map){
        return pointPackageSortService.replaceToolCode(map);
    }
    @PostMapping("replaceToolByHandle")
    public ResponseMsg replaceToolByHandle(@RequestBody HashMap map){
        return pointPackageSortService.replaceToolByHandle(map);
    }
}
